package com.huifaapp.mall.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.Homefragment.ChioceActivity;
import com.huifaapp.mall.activity.HtmlActivity;
import com.huifaapp.mall.activity.JDred_packetActivity;
import com.huifaapp.mall.activity.Red_PacketActivity;
import com.huifaapp.mall.activity.Search_showActivity;
import com.huifaapp.mall.activity.ShopYouhuiShareActivity;
import com.huifaapp.mall.activity.Specialactivity;
import com.huifaapp.mall.activity.TodaysSelectionFragment;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.ChioBean;
import com.huifaapp.mall.bean.JDlianjie;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.Contig;
import com.kepler.jd.Listener.LoginListener;
import com.kepler.jd.login.KeplerApiManager;
import com.kepler.jd.sdk.exception.KeplerBufferOverflowException;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by mac on 2018/1/30.
 */

public class ChioAdapter extends RecyclerView.Adapter<ChioAdapter.MyViewHolder> {

    private Context context;
    private List<ChioBean.DataBean.ListBean>list;
    private int location;
    private String datayouhui;
    private JDlianjie jDlianjiebean;
    private  String SYNCJDSPREADURL= ApiManager.BASE_NIUPAI_URL+Contig.typex+"/getUrl";//京东普通二合一链接
    private  String GETCONURLURL=ApiManager.BASE_NIUPAI_URL+Contig.typex+"/getConUrl";//京东获取优惠劵二合一链接
    private String datalisnajie;
    ArrayList<String> arrayList;
    private List<Boolean> isChecked;    //每个条目是否为选中
    private List<String> numbers;       //每个条目应显示的数字
    private List<Integer> checkedIndex;   //保存选中的下标
    private List<CheckBox> checkBox;      //保存选中的checkBox
    private int maxChecked = 9;       //最多选中几个
    private int checkedNumber = 0;    //选中的个数
            private int length = 1000000;  //条目的总长
    ArrayList<String> idlist;

    public ChioAdapter(Context context, List<ChioBean.DataBean.ListBean> list) {
        this.context = context;
        this.list = list;
        arrayList = new ArrayList<String>();
        isChecked = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            isChecked.add(false);
        }
        numbers = new ArrayList<>();
        for (int i = 0; i <length; i++) {
            numbers.add("");
        }
        checkedIndex = new ArrayList<>();
        checkBox = new ArrayList<>();
    }

    @Override
    public ChioAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.chioadapter,parent,false);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            String   spuPlatform = list.get(location).getSpuPlatform();
                if (Contig.typex.equals("yh")) {
                    Intent intent = new Intent(context, Red_PacketActivity.class);
                    intent.putExtra("shopid", list.get(location).getId());
                    intent.putExtra("typex", Contig.typex);
                    context.startActivity(intent);
                } else {
                    if (Contig.typex.equals("yh")) {
                        Intent intent = new Intent(context, Red_PacketActivity.class);
                        intent.putExtra("shopid", list.get(location).getId());
                        intent.putExtra("typex", Contig.typex);
                        context.startActivity(intent);
                    } else {
                        if (Contig.typex.equals("jd")) {
                            if ("".equals(list.get(location).getCouponMoney())) {
                                initJDputong();
//                                Intent intent = new Intent(context, HtmlActivity.class);
//                                intent.putExtra("data", datalisnajie);
//                                intent.putExtra("shopid", list.get(location).getId());
//                                context.startActivity(intent);
                                if(KeplerApiManager.getWebViewService().isKeplerLogined()){
                                    try {
                                        KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                    } catch (KeplerBufferOverflowException e) {
                                        e.printStackTrace();
                                    }

                                }else {
                                    final LoginListener mLoginListener = new LoginListener() {
                                        @Override
                                        public void authSuccess(Object token) {
                                            // TODO Auto-generated method stub
                                            Toast.makeText(context, token + "", Toast.LENGTH_SHORT).show();
                                            //                showToken();

                                            if (KeplerApiManager.getWebViewService().isKeplerLogined()) {
                                                try {
                                                    KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                                } catch (KeplerBufferOverflowException e) {
                                                    e.printStackTrace();
                                                }
                                            }

                                        }

                                        @Override
                                        public void authFailed(int errorCode) {
                                            // TODO Auto-generated method stub
                                            switch (errorCode) {
                                                case KeplerApiManager.KeplerApiManagerLoginErr_Init:// 初始化失败 break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_InitIng:// 初始化没有完成 break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_openH5authPageURLSettingNull://跳转url // 为null break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_getTokenErr:// 获取失败(OAuth授权之后，获取cookie过程出错) break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_User_Cancel:// 用户取消 break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_AuthErr_ActivityOpen://打开授权页面失败 break;
                                                default:
                                                    break;
                                            }
//                Toast.makeText(AllOrderActivity.this, errorCode + ":authFailed", Toast.LENGTH_SHORT).show();
                                            Log.e("jdSHOUQUAN", errorCode + ":authFailed");
                                        }
                                    };
                                    KeplerApiManager.getWebViewService().login((Activity) context, mLoginListener);
                                }
                            }
                            else{
                                if (list.get(location).getCouponMoney()==0.0) {
                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
                                    map.put("spuId", list.get(location).getId());
                                    map.put("appid", AUniqueIdentifier.getDeviceId(context));
                                    OkHttpUtils.post().params(map).url(GETCONURLURL).build().execute(new StringCallback() {
                                        @Override
                                        public void onError(Request request, Exception e) {

                                        }

                                        @Override
                                        public void onResponse(String response) {
                                            Log.e("优惠二和一数据", response);
                                            Gson gson = new Gson();
                                            jDlianjiebean = gson.fromJson(response, JDlianjie.class);
                                            datayouhui = jDlianjiebean.getData();
                                            if (jDlianjiebean.getCode().equals("10000")) {
                                                Intent intent = new Intent(context, JDred_packetActivity.class);
                                                intent.putExtra("shopid", list.get(location).getId());
                                                context.startActivity(intent);
                                            }
                                        }
                                    });
                                } else {
                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
                                    map.put("spuId", list.get(location).getId());
                                    map.put("appid", AUniqueIdentifier.getDeviceId(context));

                                    OkHttpUtils.post().params(map).url(GETCONURLURL).build().execute(new StringCallback() {

                                        private JDlianjie jDlianjiebean;

                                        @Override
                                        public void onError(Request request, Exception e) {

                                        }

                                        @Override
                                        public void onResponse(String response) {
                                            Log.e("优惠二和一数据", response);
                                            Gson gson = new Gson();
                                            jDlianjiebean = gson.fromJson(response, JDlianjie.class);
                                            datayouhui = jDlianjiebean.getData();
                                            if (jDlianjiebean.getCode().equals("10000")) {
                                                if (jDlianjiebean.getData() == null) {
                                                    if(KeplerApiManager.getWebViewService().isKeplerLogined()){
                                                        try {
                                                            KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                                        } catch (KeplerBufferOverflowException e) {
                                                            e.printStackTrace();
                                                        }

                                                    }else {
                                                        final LoginListener mLoginListener = new LoginListener() {
                                                            @Override
                                                            public void authSuccess(Object token) {
                                                                // TODO Auto-generated method stub
                                                                Toast.makeText(context, token + "", Toast.LENGTH_SHORT).show();
                                                                //                showToken();

                                                                if (KeplerApiManager.getWebViewService().isKeplerLogined()) {
                                                                    try {
                                                                        KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                                                    } catch (KeplerBufferOverflowException e) {
                                                                        e.printStackTrace();
                                                                    }
                                                                }

                                                            }

                                                            @Override
                                                            public void authFailed(int errorCode) {
                                                                // TODO Auto-generated method stub
                                                                switch (errorCode) {
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_Init:// 初始化失败 break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_InitIng:// 初始化没有完成 break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_openH5authPageURLSettingNull://跳转url // 为null break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_getTokenErr:// 获取失败(OAuth授权之后，获取cookie过程出错) break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_User_Cancel:// 用户取消 break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_AuthErr_ActivityOpen://打开授权页面失败 break;
                                                                    default:
                                                                        break;
                                                                }
//                Toast.makeText(AllOrderActivity.this, errorCode + ":authFailed", Toast.LENGTH_SHORT).show();
                                                                Log.e("jdSHOUQUAN", errorCode + ":authFailed");
                                                            }
                                                        };
                                                        KeplerApiManager.getWebViewService().login((Activity) context, mLoginListener);
                                                    }
//                                                    Intent intent = new Intent(context, HtmlActivity.class);
//                                                    intent.putExtra("shopid", list.get(location).getId());
//                                                    intent.putExtra("data", datayouhui);
//                                                    context.startActivity(intent);
                                                }
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    }
                }
            }
        });
        return new MyViewHolder(view) ;


    }
    private void initJDputong(){
        Map<String,String>map=new HashMap<String, String>();
        map.put("spuId",list.get(location).getId());
        map.put("appid", AUniqueIdentifier.getDeviceId(context));
        map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
        OkHttpUtils.post().params(map).url(SYNCJDSPREADURL).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Log.e("fgdgfe",response);
                Gson gson=new Gson();
                JDlianjie jDlianjie = gson.fromJson(response, JDlianjie.class);
                datalisnajie = jDlianjie.getData();
                Log.e("kfjsdkghdfk", datalisnajie);

            }
        });

    }
    @Override
    public void onBindViewHolder(final ChioAdapter.MyViewHolder holder, final int position) {

        location = position;
        holder.shop_name.setText(list.get(position).getGoodsName());
        Glide.with(context).load(list.get(position).getMainImageUrl()).into(holder.im_shop);
        holder.shop_xj.setText(list.get(position).getConPrice()+"");
        holder.shop_yj.setText("原价¥"+list.get(position).getPrice()+"");
        holder.shop_redbag.setText("红包券¥"+list.get(position).getCouponMoney()+"");
        holder.shop_count.setText("已抢"+list.get(position).getTotalSales()+"件");
        //解决RecyclerView和checkBox问题
        holder.cb_checked_share_chio.setTag(position);
        if (ChioceActivity.hmap.containsKey(position)) {
            holder.cb_checked_share_chio.setChecked(ChioceActivity.hmap.get(position));
        } else {
            holder.cb_checked_share_chio.setChecked(false);//true or false 都可以，看实际需求
        }
        if(SPUtils.getInstance().getString(SPConstants.KEY_ISSTORE).equals("1")){
            holder.cb_checked_share_chio.setVisibility(View.VISIBLE);
            holder.tv_lijifenxiangpt.setVisibility(View.GONE);
            holder.tv_lijifenxiang.setVisibility(View.VISIBLE);
        }else{
            holder.cb_checked_share_chio.setVisibility(View.GONE);
            holder.tv_lijifenxiangpt.setVisibility(View.VISIBLE);
            holder.tv_lijifenxiang.setVisibility(View.GONE);
        }
if(list.get(position).getWlCommission()==0.0||list.get(position).getWlCommission()==0.00){
    holder.tv_lijifenxiang.setText("立即分享");
    holder.tv_lijifenxiang_no.setText("立即分享");
}else{
        holder.tv_lijifenxiang.setText("立即分享赚 ¥" + list.get(position).getWlCommission());
        holder.tv_lijifenxiang_no.setText("立即分享赚 ¥" + list.get(position).getWlCommission());
}
        holder.tv_lijifenxiang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, ShopYouhuiShareActivity.class);
                intent.putExtra("id", list.get(position).getId());
                context.startActivity(intent);
                holder.tv_lijifenxiang_no.setVisibility(View.VISIBLE);
                holder.tv_lijifenxiang.setVisibility(View.GONE);

            }
        });
        if(list.get(position).getSpuPlatform().equals("jd")){
            holder.iv_speclia_jdOryh_chio.setImageResource(R.drawable.jingdong);
        }else if(list.get(position).getSpuPlatform().equals("yh")){
            holder.iv_speclia_jdOryh_chio.setImageResource(R.drawable.youhui);
        }
        try {


            //  不要动
            holder.cb_checked_share_chio.setChecked(isChecked.get(position));
            holder.cb_checked_share_chio.setText(numbers.get(position));
            holder.cb_checked_share_chio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    boolean check;
                    if (checkedNumber < maxChecked) {
                        if (!isChecked.get(position)) {
                            checkedIndex.add(position);
                            checkBox.add(holder.cb_checked_share_chio);
                            checkedNumber++;
                            setText();
                        } else {
                            clearText(position, holder.cb_checked_share_chio);
                        }
                        check = !isChecked.get(position);
                    } else {
                        if (checkedNumber == maxChecked && isChecked.get(position)) {
                            clearText(position, holder.cb_checked_share_chio);
                        } else {
                            Toast.makeText(context, "最多只能选" + maxChecked + "个", Toast.LENGTH_SHORT).show();
                        }
                        check = false;
                    }
                    isChecked.set(position, check);
                    holder.cb_checked_share_chio.setChecked(isChecked.get(position));
                }
            });

            Contig.checkedIndexCHIO = checkedIndex;

        } catch (Exception e) {
            Log.e("Exception", e.getMessage());
        }

        holder.tv_lijifenxiang_no.setVisibility(View.GONE);
//        holder.tv_lijishare_btn.setVisibility(View.VISIBLE);
        for (int s = 0; s < Contig.ShareListCHIO.size(); s++) {
            if (list.get(position).getId().equals(Contig.ShareListCHIO.get(s))) {
                holder.tv_lijifenxiang_no.setVisibility(View.VISIBLE);
                holder.tv_lijifenxiang.setVisibility(View.GONE);
                Log.e("5647","youbianhua          "+list.get(position).getId());


            }
        }

    }



    @Override
    public int getItemCount() {
        return list==null?0:list.size();
    }
    public void clearText(int position, CheckBox cb_checked) {
        for (int i = 0; i < checkedIndex.size(); i++) {
            if (checkedIndex.get(i) == position) {
                numbers.set(position, "");
                checkedIndex.remove(i);
                checkBox.remove(i);
                break;
            }
        }
        checkedNumber--;
        setText();
        numbers.set(position, "");
        cb_checked.setText("");
    }

    public void setText() {
        for (int i = 0; i < checkedIndex.size(); i++) {
            numbers.set(checkedIndex.get(i), (i + 1) + "");
            checkBox.get(i).setText(numbers.get(checkedIndex.get(i)));

        }
    }



    public class MyViewHolder extends RecyclerView.ViewHolder {


        TextView shop_name,shop_yj,shop_xj,shop_count,shop_redbag;
        ImageView im_shop;
        private TextView tv_lijifenxiangpt;
        private TextView tv_lijifenxiang_no;
        private TextView tv_lijifenxiang;
        private CheckBox cb_checked_share_chio;
        private ImageView iv_speclia_jdOryh_chio;

        public MyViewHolder(View itemView) {
            super(itemView);
            shop_name = (TextView) itemView.findViewById(R.id.chioce_shop_name);
            shop_xj = (TextView) itemView.findViewById(R.id.chioce_xj);
            shop_yj = (TextView) itemView.findViewById(R.id.chioce_yj);
            shop_count = (TextView) itemView.findViewById(R.id.chioce_num);
            shop_redbag = (TextView) itemView.findViewById(R.id.chioce_redbag);
            im_shop = (ImageView) itemView.findViewById(R.id.chioce_shopim);
            tv_lijifenxiangpt= (TextView) itemView.findViewById(R.id.tv_lijifenxiangpt);
            tv_lijifenxiang_no= (TextView) itemView.findViewById(R.id.tv_lijifenxiang_no);
            tv_lijifenxiang= (TextView) itemView.findViewById(R.id.tv_lijifenxiang);
            cb_checked_share_chio= (CheckBox) itemView.findViewById(R.id.cb_checked_share_chio);
            iv_speclia_jdOryh_chio= (ImageView) itemView.findViewById(R.id.iv_speclia_jdOryh_chio);


        }
    }

}
